package com.game.doudizhu.service;

import com.game.doudizhu.model.Player;
import com.game.doudizhu.model.PlayerRank;
import com.game.doudizhu.repository.PlayerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RankingService {
    
    @Autowired
    private PlayerRepository playerRepository;
    
    @Autowired
    private AchievementService achievementService;

    @Cacheable(value = "rankings", key = "'score'")
    public List<PlayerRank> getScoreRankings() {
        List<Player> players = playerRepository.findAll();
        
        return players.stream()
            .map(this::convertToRank)
            .sorted((r1, r2) -> r2.getScore().compareTo(r1.getScore()))
            .limit(100)
            .collect(Collectors.toList());
    }

    @Cacheable(value = "rankings", key = "'winrate'")
    public List<PlayerRank> getWinRateRankings() {
        List<Player> players = playerRepository.findAll();
        
        return players.stream()
            .map(this::convertToRank)
            .sorted((r1, r2) -> r2.getWinRate().compareTo(r1.getWinRate()))
            .limit(100)
            .collect(Collectors.toList());
    }

    @Cacheable(value = "rankings", key = "'achievement'")
    public List<PlayerRank> getAchievementRankings() {
        List<Player> players = playerRepository.findAll();
        
        return players.stream()
            .map(player -> {
                PlayerRank rank = convertToRank(player);
                rank.setAchievementCount(achievementService.getPlayerAchievementCount(player.getId()));
                return rank;
            })
            .sorted((r1, r2) -> r2.getAchievementCount().compareTo(r1.getAchievementCount()))
            .limit(100)
            .collect(Collectors.toList());
    }
    
    private PlayerRank convertToRank(Player player) {
        PlayerRank rank = new PlayerRank();
        rank.setPlayerId(player.getId());
        rank.setUsername(player.getUsername());
        rank.setScore(player.getScore());
        rank.setGamesPlayed(player.getGamesPlayed());
        rank.setGamesWon(player.getGamesWon());
        rank.setWinRate(calculateWinRate(player));
        return rank;
    }
    
    private double calculateWinRate(Player player) {
        if (player.getGamesPlayed() == 0) return 0.0;
        return (double) player.getGamesWon() / player.getGamesPlayed() * 100;
    }
} 